package com.common.security.service;

import cn.hutool.core.lang.UUID;
import com.common.core.constants.CacheConstants;
import com.common.core.constants.JwtConstants;
import com.common.redis.service.RedisService;
import com.common.core.domain.LoginUser;
import com.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenService {
    @Resource
    RedisService redisService;

    //创建token
    public String createToken(Long userId,String secret,int identity,String nickName, String headImage){
        //生成JWT
        Map<String, Object> claims =new HashMap<>();
        String userKey= UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID,userId);
        claims.put(JwtConstants.LOGIN_USER_KEY,userKey);
        String jwt= JwtUtils.createToken(claims,secret);

        //将敏感信息存储到redis中,key就是userKey
        LoginUser loginUser=new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        String key=getToken(userKey) ;     //组合后存入
        redisService.setCacheObject(key,loginUser,CacheConstants.EXP, TimeUnit.MINUTES);

        return jwt;
    }

    //延长token有效时间,在身份验证之后,controller之前执行
    //因此在拦截器上延长更合适
    public void extendToken(Claims claims){
        String userKey = getUserKey(claims);
        if(userKey==null){
            return ;
        }
        String tokenKey=getToken(userKey);
        Long time=redisService.getExpire(tokenKey,TimeUnit.MINUTES);
        if(time!=null && time<CacheConstants.REFRESH_TIME){
            redisService.expire(tokenKey,CacheConstants.EXP,TimeUnit.MINUTES);
        }
    }

    public LoginUser getLoginUser(String token,String secret) {
        String userKey = getUserKey(token, secret);
        if(userKey==null){
            return null;
        }
        return redisService.getCacheObject(getToken(userKey),LoginUser.class);
    }

    public boolean deleteLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if(userKey==null){
            return false;
        }
        return redisService.deleteObject(getToken(userKey));
    }

    //获取用户Id
    public Long getUserId(String token,String secret){
        Claims claims=getClaims(token,secret);
        return Long.valueOf(JwtUtils.getUserId(claims));
    }

    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims));  //获取jwt中的key
    }

    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    private String getUserKey(String token,String secret){
        Claims claims=getClaims(token,secret);
        return JwtUtils.getUserKey(claims);
    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getToken(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token：{}, 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{}, 出现异常", token, e);
            return null;
        }
        return claims;
    }

    private String getToken(String userKey){
        return CacheConstants.LOGIN_TOKEN_KEY+userKey;
    }
}
